#include "Camera.h"
Camera::Camera(): farClip(defaultFarClip), nearClip(defaultNearClip), screenAspect(defaultScreenAspect), fovY(defaultFOVY){

}

void Camera::glLookAt(Vec3f eye, Vec3f center, Vec3f up){
	::glMatrixMode(GL_MODELVIEW);
	::glLoadIdentity();

	Vec3f vN = eye-center;
	Vec3f vU = up.cross(vN);
	vU=vU.normalize();
	vN=vN.normalize();
	Vec3f vV = vN.cross(vU);
	float fModelView2[16] =
	{
	   vU.x,			vV.x,			vN.x,			0.0f,
	   vU.y,			vV.y,			vN.y,			0.0f,
	   vU.z,			vV.z,			vN.z,			0.0f,
	   -eye.dot(vU),	-eye.dot(vV),	-eye.dot(vN),	1.0f
	};
	memcpy(fModelView.f,fModelView2,16*4);
	::glLoadMatrixf(fModelView.f);

}

PVRTMATRIXf Camera::getModelViewMatrix(){
	return fModelView;
}

float Camera::getFarClip(){
	return farClip;
}
float Camera::getNearClip(){
	return nearClip;
}

void Camera::setFarClip(float zClip){
	farClip=zClip;
	loadPerspectiveMatrix();
}

void Camera::loadPerspectiveMatrix(){
	::glMatrixMode(GL_PROJECTION);
	::glLoadIdentity();

	float f = 1.0f / tanf(fovY * (3.1416f / 360.f));
	float z1 = (farClip + nearClip) / (nearClip - farClip);
	float z2 = (2 * farClip * nearClip) / (nearClip - farClip);

	float m[] =
	{
		-f / screenAspect,  0,      0,      0,
		0,           f,      0,      0,
		0,           0,     z1,     -1,
		0,           0,     z2,      0
	};
	::glMultMatrixf(m);
}

void Camera::loadPerspectiveMatrix(float fovy, float aspect, float zNear, float zFar){
	::glMatrixMode(GL_PROJECTION);
	::glLoadIdentity();

	farClip=zFar;
	nearClip=zNear;
	screenAspect=aspect;
	fovY=fovy;

	float f = 1.0f / tanf(fovY * (3.1416f / 360.0f));
	float z1 = (farClip + nearClip) / (nearClip - farClip);
	float z2 = (2 * farClip * nearClip) / (nearClip - farClip);

	float m[] =
	{
		-f / screenAspect,  0,      0,      0,
		0,           f,      0,      0,
		0,           0,     z1,     -1,
		0,           0,     z2,      0
	};
	::glMultMatrixf(m);
}

void Camera::Projection3D(){
		
		loadPerspectiveMatrix();

		Vec3f eye = Vec3f(0.0f,-40,0.0f);
		Vec3f center = Vec3f(0.0f,0.0f,0.0f);
		Vec3f up = Vec3f(0.0f, 0.0f, 1.0f);
		glLookAt(eye,center,up);
}



